package com.b511.swpu.cementbackend.service.impl;

import com.b511.swpu.cementbackend.dao.*;
import com.b511.swpu.cementbackend.dto.input.NavigationInputDto;
import com.b511.swpu.cementbackend.dto.input.RegisterInputDto;
import com.b511.swpu.cementbackend.dto.input.SqlDto;
import com.b511.swpu.cementbackend.dto.output.ParentOutDto;
import com.b511.swpu.cementbackend.entity.*;
import com.b511.swpu.cementbackend.exception.CementException;
import com.b511.swpu.cementbackend.repository.*;
import com.b511.swpu.cementbackend.service.DataQueryService;
import com.b511.swpu.cementbackend.service.SysManageService;
import com.b511.swpu.cementbackend.util.*;
import com.b511.swpu.cementbackend.util.enumeration.Code;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class SysManageServiceImpl implements SysManageService{

    private final SYSM_DataDictRepository sysManageRepository;
    private final SYSM_CompanyRepository sysm_companyRepository;
    private final SYSM_EmployeeRepository sysm_employeeRepository;
    private final BA_WellRepository ba_wellRepository;
    private final SysUserRepository sysUserRepository;
    private final MAIN_OrganizationRepository main_organizationRepository;
    private final Sys_User_RolesRepository sys_user_rolesRepository;
    private final SysRoleRepository sysRoleRepository;
    private final DataQueryService dataQueryService;
    private final MAIN_PersonRepository main_personRepository;
    private final SYS_NavigationRepository sys_navigationRepository;
    private final Sys_Role_NavigationRepository sys_role_navigationRepository;
    private final SysMenuRepository sysMenuRepository;
    EmployeeManageRepository employeeManageRepository=new EmployeeManageRepository();
    DBHelper dbHelper=new DBHelper();
    @Autowired
    MAIN_PersonDao main_personDao;

    @Autowired
    SysRoleDao sysRoleDao;

    @Autowired
    Sys_Role_Sys_MenusDao sys_role_sys_menusDao;

    @Autowired
    Sys_Role_NavigationDao sys_role_navigationDao;

    @Autowired
    Sys_User_RolesDao sys_user_rolesDao;

    @Autowired
    SysUserDao sysUserDao;

    @Resource
    private AnotherTreeUtil anotherTreeUtil;

    public SysManageServiceImpl(SYSM_DataDictRepository sysManageRepository, SYSM_CompanyRepository sysm_companyRepository, SYSM_EmployeeRepository sysm_employeeRepository, BA_WellRepository ba_wellRepository, SysUserRepository sysUserRepository, MAIN_OrganizationRepository main_organizationRepository, Sys_User_RolesRepository sys_user_rolesRepository, SysRoleRepository sysRoleRepository, DataQueryService dataQueryService, MAIN_PersonRepository main_personRepository, SYS_NavigationRepository sys_navigationRepository, Sys_Role_NavigationRepository sys_role_navigationRepository, SysMenuRepository sysMenuRepository) {
        this.sysManageRepository = sysManageRepository;
        this.sysm_companyRepository = sysm_companyRepository;
        this.sysm_employeeRepository = sysm_employeeRepository;
        this.ba_wellRepository = ba_wellRepository;
        this.sysUserRepository = sysUserRepository;
        this.main_organizationRepository = main_organizationRepository;
        this.sys_user_rolesRepository = sys_user_rolesRepository;
        this.sysRoleRepository = sysRoleRepository;
        this.dataQueryService = dataQueryService;
        this.main_personRepository = main_personRepository;
        this.sys_navigationRepository = sys_navigationRepository;
        this.sys_role_navigationRepository = sys_role_navigationRepository;
        this.sysMenuRepository = sysMenuRepository;
    }

    @Override
    public R getDataDictTree() {
        List<SYSM_DataDict> all = sysManageRepository.findAll();
        return R.ok().putData(anotherTreeUtil.getDataDictTree(all));
    }

    @Override
    public R getCompanyStructureTree() {
        List<SYSM_Company> all=sysm_companyRepository.findAll();
        return R.ok().putData(anotherTreeUtil.getCompanyStructureTree(all));
    }

    @Override
    public R getEmployeeManage(int num,int size) throws Exception {

        JSONObject employeeManage = employeeManageRepository.findEmployeeManage(num,size);

        return R.ok().putData(employeeManage);


//另一种方式查询
//        List<EmployeeManageOutDto> employeeManage = sysm_employeeRepository.findEmployeeManage();
//        int total=employeeManage.size();
//        PageUtil pageUtil=new PageUtil(employeeManage,10);
//        return R.ok().putData(pageUtil.getPage(1));
    }

    @Override
    public R getOneDataDict(String code) {
        return R.ok().putData(sysManageRepository.findByDICTCODEChild(code,code.length()));
    }

    @Override
    public R getDataDictByName(String name) {
        SYSM_DataDict sysmDataDict = sysManageRepository.findCodeByNAME(name);
        if (null == sysmDataDict) {
            throw new CementException(Code.SELECT_FAIL);
        }
        return R.ok().putData(sysManageRepository.findByDICTCODEChild(sysmDataDict.getDICTCODE(), sysmDataDict.getDICTCODE().length()));

    }

    @Override
    public R getArea() {
        return R.ok().putData(ba_wellRepository.findDistinctArea());
    }

    @Override
    public R getWellType() {
        return R.ok().putData(ba_wellRepository.findDistinctWellType());
    }

    @Override
    public R getCaseSize() {
        return R.ok().putData(ba_wellRepository.findCaseSize());
    }

    @Override
    public R getWellSpacing() {
        return R.ok().putData(ba_wellRepository.findDistinctWellSpacing());
    }

    @Override
    public R queryByName(String companyname,String departmentName, String name,Integer num,Integer size) {
        Pageable pageable = PageRequest.of(num,size);
        //name模糊查询
        name=name+"%";
        if ((!"".equals(companyname))&&(!"".equals(departmentName))&&(!"".equals(name)))
            return R.ok().putData(sysUserRepository.queryPersonBy1(companyname,departmentName,name,pageable));

        else if ((!"".equals(companyname))&&(!"".equals(departmentName))&&("".equals(name)))
            return R.ok().putData(sysUserRepository.queryPersonBy2(companyname,departmentName,pageable));

        else if ((!"".equals(companyname))&&("".equals(departmentName))&&(!"".equals(name)))
            return R.ok().putData(sysUserRepository.queryPersonBy3(companyname,name,pageable));

        else if (("".equals(companyname))&&(!"".equals(departmentName))&&(!"".equals(name)))
            return R.ok().putData(sysUserRepository.queryPersonBy4(departmentName,name,pageable));

        else if ((!"".equals(companyname))&&("".equals(departmentName))&&("".equals(name)))
            return R.ok().putData(sysUserRepository.queryPersonBy5(companyname,pageable));

        else if (("".equals(companyname))&&(!"".equals(departmentName))&&("".equals(name)))
            return R.ok().putData(sysUserRepository.queryPersonBy6(departmentName,pageable));

        else if (("".equals(companyname))&&("".equals(departmentName))&&(!"".equals(name))){
            return R.ok().putData(sysUserRepository.queryPersonBy7(name,pageable));
        }

        else
            return R.ok().putData(sysUserRepository.userAndPerson(pageable));
    }

    @Override
    public R queryCompanyTree() {
        List<MAIN_Organization> all = main_organizationRepository.findAll();
        List<ParentOutDto> list = new ArrayList<>();
        for (MAIN_Organization company:all){
            list.add(new ParentOutDto(company.getCode(), company.getParentCode(), company.getName()));
        }
        TreeNodeUtils treeNodeUtils = new TreeNodeUtils(list);
        ParentOutDto root = treeNodeUtils.generateTree("10003191");
        // System.out.println(root);
        return R.ok().putData(root);
    }

    @Override
    public R register(RegisterInputDto registerInputDto) {
        if(sysUserRepository.findByUsername(registerInputDto.getUsername())!=null){
            return R.error("当前用户已存在，请修改用户名");
        }else {
            SysUser sysUser=new SysUser();
            sysUser.setMan(false);
            sysUser.setEnable(true);
            sysUser.setPassword(MD5Util.md5Encrypt32Upper(registerInputDto.getPassword()));
            sysUser.setName(registerInputDto.getCode());//sys_user表中的name=main_person表中的code
            sysUser.setUsername(registerInputDto.getUsername());
            SYSM_Company sysm_company=new SYSM_Company();
            sysm_company.setCOMPANYID(16L);
            sysUser.setCompany(sysm_company);
            MetaSystemUnit metaSystemUnit=new MetaSystemUnit();
            metaSystemUnit.setId(635L);
            sysUser.setMetaSystemUnit(metaSystemUnit);
            //添加Sys_User_Roles信息
            SysRole sysRole=sysRoleRepository.findByName(registerInputDto.getSysrole());
            List<SysRole> list=new LinkedList<>();
            list.add(sysRole);
            sysUser.setRoles(list);
            sysUserRepository.save(sysUser);
            return R.ok();
        }

    }

    @Override
    public R logout(String name) throws Exception {
        SysUser user = sysUserRepository.findByName(name);
        if (user != null) {
            String id = user.getId();
            //先删除sys_user_roles中的数据
            sys_user_rolesDao.deleteBySys_User_Id(id);
            //再删除sys_user中的数据
            sysUserDao.deleteByID(id);
            return R.ok();
        }
        return R.error("该用户名不存在");
    }

    @Override
    public R querySysRole() {
        return R.ok().putData(sysRoleRepository.findSysRole());
    }

    @Override
    public R queryCompanyName() {
        return R.ok().putData( main_organizationRepository.findCompanyName("2"));
    }

    @Override
    public R querydepartmentName() {
        return R.ok().putData( main_organizationRepository.findDepartmentName("4"));
    }

    @Override
    public R createMainPerson(MAIN_Person main_person) {
        MAIN_Person person = main_personRepository.findByCode(main_person.getCode());
        if (person==null){
            //relationcode人工自增
            Integer maxCode = main_personRepository.findMaxRelationCode();
            maxCode+=1;
            main_person.setRelationCode(maxCode.toString());
            //这里前端没有返回companyname，只能手动查
            String layer4ParentCode=main_organizationRepository.findParentCode(main_person.getGroupCode());
            String layer3ParentCode=main_organizationRepository.findParentCode(layer4ParentCode);
            String companyname=main_organizationRepository.findName(layer3ParentCode);
            main_person.setCompanyName(companyname);
            main_personRepository.save(main_person);
            return R.ok();
        }else{
            return R.error("员工编码已存在");
        }
    }

    @Override
    public R queryMainPerson(String code) {
        return R.ok().putData(main_personRepository.findByCode(code));
    }

    @Override
    public R updateMainPerson(MAIN_Person main_person) {
        //这里前端没有返回companyname，只能手动查
        String layer4ParentCode=main_organizationRepository.findParentCode(main_person.getGroupCode());
        String layer3ParentCode=main_organizationRepository.findParentCode(layer4ParentCode);
        String companyname=main_organizationRepository.findName(layer3ParentCode);
        main_person.setCompanyName(companyname);
        main_personRepository.save(main_person);
        return R.ok();
    }

    @Override
    public R deleteMainPerson(String code) {
        if(main_personRepository.findByCode(code)!=null){
            main_personDao.deleteByCode(code);
            return R.ok();
        }else {
            return R.error("用户不存在");
        }

    }

    @Override
    public R queryAllNavigation() {
        List<SYS_Navigation> all = sys_navigationRepository.findAll();
        return R.ok().putData(anotherTreeUtil.getNavigationTree2(all));
    }

    @Override
    public R queryNavigationByRole(String sysrole) {
        //取到sys_role_id
        String sys_role_id = sysRoleRepository.findIdByName(sysrole);
        //根据sys_role_id来找到所有的sys_navigation_Id
        List<String> navigationIds = sys_role_navigationRepository.findByRoleID(sys_role_id);
        return R.ok().putData(navigationIds);
    }

    @Override
    public R queryNavigationBysysrole(String sysrole) {
        //取到sys_role_id
        String sys_role_id = sysRoleRepository.findIdByName(sysrole);
        //根据sys_role_id来找到所有的sys_navigation_Id
        List<String> navigationIds = sys_role_navigationRepository.findByRoleID(sys_role_id);
        if (navigationIds.size() > 0) {
            List<SYS_Navigation> res=new LinkedList<>();
            for(String e:navigationIds){
                SYS_Navigation sys_navigation = sys_navigationRepository.findByNavigationId(e);
                res.add(sys_navigation);
            }
            return R.ok().putData(anotherTreeUtil.getNavigationTree2(res));
        }else {
            return R.error("权限为空");
        }
    }

    @Override
    public R updateNavigationByRole(NavigationInputDto navigationInputDto) {
        String rolename=navigationInputDto.getSysrole();
        String roleid=sysRoleRepository.findIdByName(rolename);
        if(roleid!=null){
            //先删除改roleid下的所有权限
            sys_role_navigationDao.deleteByRoleID(roleid);
            //再添加权限
            for(String id:navigationInputDto.getRoles()){
                Sys_Role_Navigation sys_role_navigation=new Sys_Role_Navigation();
                sys_role_navigation.setSys_Role_ID(roleid);
                sys_role_navigation.setSys_Navigation_ID(id);
                sys_role_navigationDao.saveIt(sys_role_navigation);
            }
            return R.ok();
        }else {
            return R.error("没有该角色");
        }
    }

    @Override
    public R queryAllRole(Integer num,Integer size) {
        Pageable pageable = PageRequest.of(num,size);
        return R.ok().putData( sysRoleRepository.findAll(pageable));
    }

    @Override
    public R createNewRole(SysRole newrole) {
        SysRole role = sysRoleRepository.findByName(newrole.getName());
        if (role==null){
            SysRole sysRole=new SysRole();
            sysRole.setName(newrole.getName());
            List<SysMenu> sysMenus = sysMenuRepository.findAll();
            System.out.println(sysMenus);
            sysRole.setSysMenus(sysMenus);
            sysRoleRepository.save(sysRole);
            return R.ok();
        }else {
            return R.error("角色名已存在");
        }
    }

    @Override
    public R updateRole(String name, String id) {
        SysRole role = sysRoleRepository.findRoleById(id);
        if(role!=null){
            role.setName(name);
            sysRoleRepository.save(role);
            return R.ok();
        }else {
            return R.error("该角色不存在");
        }

    }

    @Override
    public R deleteRole(String role_id) {
        //判断是否有这个角色
        if(sysRoleRepository.findRoleById(role_id)==null){
            return R.error("该角色不存在");
        }else {
            // 先判断这个角色下是否还有用户，如果有就不能删除
            List<Sys_User_Roles> sys_user_roles = sys_user_rolesRepository.findByRoleID(role_id);
            if(sys_user_roles.size()!=0){
               return R.error("该角色下还有部分用户，请先删除用户后再删除角色");
            }
            System.out.println("准备删除表中数据");
            //删除sys_role_sys_menus中得数据
            sys_role_sys_menusDao.deleteBySys_Role_id(role_id);
            //删除sys_role_navigation得数据
            sys_role_navigationDao.deleteByRoleID(role_id);
            //删除sysrole表中得数据
            sysRoleDao.deleteById(role_id);
            return R.ok();
        }
    }

    @Override
    public R queryAllRoleLikeName(String name, Integer num, Integer size) {
        Pageable pageable = PageRequest.of(num,size);
        name=name+"%";
        return R.ok().putData( sysRoleRepository.queryAllRoleLikeName(name,pageable));
    }

    @Override
    public R queryRoleByID(String id) {
        SysRole role = sysRoleRepository.findRoleById(id);
        if (role!=null){
            return R.ok().putData(role);
        }else{
            return R.error("角色不存在");
        }

    }
}
